from django.views.generic import ListView, DeleteView, CreateView, DetailView
from django.contrib import messages
from KeHu.models import KeHu
# import KeHu.models
from .models import Chanpin,Dingdan
from .forms import ChanpinForm
from django.db.models import Q
from datetime import datetime
from .forms import KeHuDingdanForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from KeHu.models import KeHugenjinlog
from jiaowu_xueyuan.models import Xueyuan_zongbiao
from datetime import datetime

from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from django.views.generic import ListView, DeleteView, CreateView, DetailView

from KeHu.models import KeHu,KeHuzilao
from KeHu.models import KeHugenjinlog
from jiaowu_xueyuan.models import  Xueyuan_zongbiao
from .forms import ChanpinForm
from .forms import KeHuDingdanForm
# import KeHu.models
from .models import Chanpin, Dingdan
from qxcrm_index.tool_user_zhanneixin import zhanneixin_index # 引入zhanneixin_index函数 站内信
from django.contrib.auth.models import User

# Create your views here.


class product_list(ListView):
    model = Chanpin
    template_name = 'chanpin_list.html'
    context_object_name = 'chanpins'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['bigtitle'] = '产品列表'
        return context
    def get_queryset(self):
        return Chanpin.objects.all()

class ChanpinCreateView(CreateView):
    model = Chanpin
    form_class = ChanpinForm
    template_name = 'chanpin_add.html'
    success_url = 'product_list'

class Add_Kehu_Dd(LoginRequiredMixin,CreateView):
    model = Dingdan
    form_class = KeHuDingdanForm
    template_name = 'add_dd.html'

    def form_valid(self, form):
        self.object = form.save(commit=False)
        kehu_pk = self.kwargs['pk']  # 获取 URL 中的 pk 参数
        kehu_instance = get_object_or_404(KeHu, pk=kehu_pk)  # 使用 pk 参数获取 KeHu 实例
        print("form_valid_kehu_instance: ", kehu_instance)
        #kehuziliao_instance=get_object_or_404(KeHuzilao, kehu=kehu_instance)
        self.object.kehu = kehu_instance  # 将 KeHu 实例赋值给 Dingdan 实例的 kehu 字段
        self.object.dduser = self.request.user  # 将当前用户实例赋值给 Dingdan 实例的 dduser 字段
        self.object.kehu = kehu_instance  # 将 KeHu 实例赋值给 Dingdan 实例的 kehu 字段
        # 获取表单中 ddchanpin 字段的值（这通常是一个 ID 列表）
        # ddchanpin_ids = form.cleaned_data.get('ddchanpin')  # 确保你的表单字段名是 ddchanpin
        # for ddchanpin_id in ddchanpin_ids:
        #     leibie_id = ddchanpin_id.leibie.id
        #     ddchanpinnemen = Chanpin.objects.get(id=ddchanpin_id.id).title
        self.object.save()
        try:
            zongbiao_instances = Xueyuan_zongbiao.objects.get(kehu=kehu_instance)
            zongbiao_instances.xueyuan_dingdan.add(self.object)
            # 无需再调用 zongbiao_instance.save()，因为 add() 方法会自动处理多对多关系的更新
            zongbiao_instances.save()  # 别忘了保存更改
        except Xueyuan_zongbiao.DoesNotExist:
            zongbiao_instances = Xueyuan_zongbiao(
                kehu=kehu_instance,
                xueyuan_jinbantime=datetime.now(),
                baomingtime=datetime.now(),
            )
            # 设置多对多关系
            # 保存实例，多对多关系也会被保存
            zongbiao_instances.chengjiao_laoshi= self.request.user
            zongbiao_instances.save()
            zongbiao_instances.xueyuan_dingdan.add(self.object)

        except Exception as e:
            print("An error occurred:", e)
            messages.error(self.request,f'创建订单成功|{e}')

        try:
            ###运行正确
            kehugenjinlog_instance = KeHugenjinlog(
                kehu=kehu_instance,
                genjinleixing=1,
                genjintext=f'{self.request.user}为{kehu_instance}新增订单{self.object}',
                genjintime=datetime.now(),
                genjin_user=self.request.user,
            )
            kehugenjinlog_instance.save()
        except Exception as e:
            print("An error occurred:", e)
            messages.error(self.request,f'创建订单成功|{e}')
        return super().form_valid(form)
    def get_success_url(self):
        kehu_pk = self.kwargs['pk']  # 获取 URL 中的 pk 参数
        kehu_instance = get_object_or_404(KeHu, pk=kehu_pk)  # 使用 pk 参数获取 KeHu 实例
        success_url = reverse_lazy('Kehu_detail', kwargs={'pk': kehu_instance.id})+f'#v-pills-profile'
        return success_url
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['bigtitle'] = '新增订单'
        kehu_pk = self.kwargs['pk']  # 获取 URL 中的 pk 参数
        kehu_instance = get_object_or_404(KeHu, pk=kehu_pk)  # 使用 pk 参数获取 KeHu 实例
        context['kehuxaingqing'] = kehu_instance

        return context



class Chanpin_dd_DeleteView(DeleteView):
    model = Dingdan
    template_name = 'chanpin_dd_del.html'
    success_url_name = 'Kehu_detail'  # 用于反转的 URL 名称

    def get_success_url(self):
        # 从URL的kwargs中获取动态参数khid
        khid = self.kwargs.get('khid')
        print(khid)
        success_url = reverse_lazy(self.success_url_name, kwargs={'pk': khid})
        query_params = '#v-pills-profile'
        return f'{success_url}{query_params}'


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

class my_cp_ddListView(ListView):
    model = Dingdan
    template_name = 'mydd_list.html'
    context_object_name = 'mydd'
    ordering = ['-id']  # 按照id降序排列


    def get_queryset(self):
        search = self.request.GET.get('search', '')
        current_user = self.request.user

        if current_user.is_superuser:
            queryset = Dingdan.objects.all()
        else:
            queryset = Dingdan.objects.filter(dduser=current_user)
        if search:
            # 假设您想根据订单号(ddh)或订单产品名称(ddchanpin__title)进行搜索
            # 您可以根据需要添加更多的搜索字段
            search_query = Q(ddh__icontains=search) | Q(ddchanpin__title__icontains=search)| Q(kehu__username__icontains=search)
            queryset = queryset.filter(search_query)

        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        months = [(i + 1) for i in range(12)]
        now = datetime.now()
        current_month = now.month
        context['months']=months
        context['current_month'] = current_month
        return context

class my_cp_ddDetailView(DetailView):
    model = Dingdan
    template_name = 'my_dd_detail.html'
    extra_context = {'ddh': '订单号'}
    context_object_name = 'ddxq'
    bigtitle = "订单详情"


